import { message } from 'antd'
import { cloneDeep, merge } from 'lodash'
import { hashHistory } from 'dva/router'
import { advertisementAudit,queryAllAddress, getDetail, AllEstateList, allActivityList, submit, getDiscity } from './buoyManagementDetailServ.js'
import { makeAddress } from "utils/util"
import moment from 'moment'
const delay = (ms) => new Promise((resolve) => {

  setTimeout(resolve, ms);

});
const defultState = {
  //推荐楼盘
  query: {
    provinceCodes: [''],
    cityCodes: [[]],
    wholeCountry: false,
    imgUrl: []
  },
  clique: '',
  city: [],
  actionType: '',
  areaList1: [],
  projectList: [],
  visible: false,
  value: 1,
  local: false,
  num: '',
  channelIndex: 1,
  biz: {
    1: {
      queryForm: {},
      rowSelection_type: 'radio',
      selectedRowKeys: []
    },
    2: {
      queryForm: {},
      rowSelection_type: 'radio',
      selectedRowKeys: []
    },
    3: {
      queryForm: {},
      rowSelection_type: 'radio',
      selectedRowKeys: []
    },
    4: {
      queryForm: {},
      rowSelection_type: 'radio',
      selectedRowKeys: []
    },
    5: {
      queryForm: {},
      rowSelection_type: 'radio',
      selectedRowKeys: []
    },
    6: {
      queryForm: {},
      rowSelection_type: 'radio',
      selectedRowKeys: []
    },
    7: {
      queryForm: {},
      rowSelection_type: 'radio',
      selectedRowKeys: []
    },
    9: {
      queryForm: {},
      rowSelection_type: 'radio',
      selectedRowKeys: []
    },
    10: {
      queryForm: {},
      rowSelection_type: 'radio',
      selectedRowKeys: []
    },
    11: {
      queryForm: {},
      rowSelection_type: 'radio',
      selectedRowKeys: []
    },
    12: {
      queryForm: {},
      rowSelection_type: 'radio',
      selectedRowKeys: []
    },
    13: {
      queryForm: {},
      rowSelection_type: 'radio',
      selectedRowKeys: []
    },
  },
  biz2: {
    queryForm: {},
    rowSelection_type: 'radio',
  },
  hrefModalObj: {
    visible: false,
    hrefType: '',
  },
  currentItem: [],
  clique: '',
  btnLoading: false,
  discityList: [],
  confirmAudit: false,
  ignoreReason: false,
  auditDesc: "", //驳回原因
   // 加载中状态
   loadingGroup:{
    '0': false,
    '-1': false,
    '1': false,
    '2': false,
  }
}

const tmpModule = {
  state: cloneDeep(defultState),
  subscriptions: {
    setup({ dispatch, history }) {
      let clique = localStorage.getItem('clique')
      history.listen(({ pathname, query }) => {
        if ('' + tmpModule.pathname === '' + pathname) {
          dispatch({ type: 'updateStore', payload: cloneDeep(defultState) });
          dispatch({ type: 'updateStore', payload: { actionType: query.actionType, slideshowId: query.slideshowId, clique: localStorage.getItem('clique') } })
          dispatch({ type: 'getAreaList', payload: {} })
        }
      })
    }
  },



  effects: {
    //获取省市
    *getAreaList({ payload }, { put, call, select }) {
      let { actionType, slideshowId, clique } = yield select((state) => state[tmpModule.namespace])
      const { data, success } = yield call(queryAllAddress);
      if (success) {
        let arr = []
        data.map((item, index) => {
          arr.push(item.value)
        })
        let areaList1 = []
        if (JSON.parse(clique)) {
          let arr = [data[0]]
          let attr = [data[data.length - 1]]
          data[0] = {
            label: "北京",
            value: "110100",
            children: arr
          }
          data[data.length - 1] = {
            label: "澳门",
            value: "820000",
            children: attr
          }
        }
        // //去掉第三级，
        // areaList = makeAddress(data,2)
        areaList1 = makeAddress(data, 2)
        areaList1 = data
        areaList1.shift()
        yield put({ type: 'updateStore', payload: { areaList1, roleArea: arr } })
        if (actionType == 'detail' || actionType == 'edit') {
          yield put({ type: 'getDetail', payload: { advertisementBuoysId: slideshowId } })
        }
      }
    },
    //获取活动详细信息
    *getDetail({ payload }, { put, call, select }) {
      const { data, success } = yield call(getDetail, payload);
      if (success) {
        //回来的数据回显
        // debugger
        let { city, areaList1, currentItem, roleArea } = yield select((state) => state[tmpModule.namespace]);

        let hrefModalObj = {};
        hrefModalObj.linkUrl = data.linkUrl || "";
        hrefModalObj.hrefType = data.linkType || "";
        hrefModalObj.btnName = data.btnName || "";
        console.dir(data);
        if (data.wholeCountry) {
          data.provinceCodes = ['0']
          data.cityCodes = []
        } else {
          for (var i = 0; i < data.provinceCodes.length; i++) {
            if (roleArea.indexOf(data.provinceCodes[i]) == -1) {
              delete data.provinceCodes[i];
            }
            for (var y = 0; y < areaList1.length; y++) {
              if (data.provinceCodes[i] == areaList1[y].value) {
                city[i] = areaList1[y].children;
              }
            }
            city.map(item => {
              item.map(child => {
                child.disabled = true;
              })
            })
          }
        };
        //(1:推介 2：内部链接 3：资讯 4:外部链接 5：活动，6：预约看房，7：美房详情)
        if (['1', '6', '7'].indexOf(data.linkType + "") > -1) {
          currentItem = [data.productId]
        } else if (['5', '3'].indexOf(data.linkType + "") > -1) {
          currentItem = [data.contentId]
        } else if (['2'].indexOf(data.linkType + "") > -1) {
          currentItem = data.linkUrl && [data.linkUrl.split('=')[1]]
        };
        if (data.url) {
          data.imgUrl = data.url
          delete data.url
        };
        hrefModalObj.params = { contentId: data.contentId, productId: data.productId, btnName: data.btnName };
        yield put({ type: 'getActivityList', payload: { businessId: data.productId } });
        yield put({ type: 'updateStore', payload: { city, query: data, hrefModalObj, currentItem } });
      }

    },
    *getDiscity({ payload }, { put, call, select }) {
      let pId = payload.pId;
      let { discityList } = yield select((state) => state[tmpModule.namespace])
      let { success, rows } = yield call(getDiscity, pId)
      if (success) {
        let arr = rows.filter(item => {
          return !discityList.includes(item.cityCode)
        }).map(item => item.cityCode)
        yield put({ type: 'updateStore', payload: { discityList: [...discityList, ...arr] } })
      }
    },

    //提交表单
    *submit({ payload }, { put, call, select }) {
      if(JSON.stringify(payload) == '{}'){
        yield put({ type: 'updateStore', payload: { btnLoading: true } })
      }
      let { query, hrefModalObj, actionType, areaList1, city } = yield select((state) => state[tmpModule.namespace])
      let objParmas = {}
      if (query.imgUrl.length == 0) {
        message.error('请上传浮标图片')
        yield put({ type: 'updateStore', payload: { btnLoading: false } })
        return false
      }
      if (!query.wholeCountry && (new Date(query.endTime).getTime() - new Date(query.startTime).getTime() > 15 * 24 * 3600 * 1000)) {
        if (new Date(query.endTime).getTime() - new Date(query.startTime).getTime() > 15 * 24 * 3600 * 1000) {
          yield put({ type: 'updateStore', payload: { btnLoading: false } })
          message.error('设置生效日期的范围最长不能超过15天')
          return false
        }
      }
      let params = hrefModalObj.params
      query.linkType = hrefModalObj.hrefType
      objParmas = {
        ...cloneDeep(query),
        ...cloneDeep(hrefModalObj),
        ...params
      }
      if (objParmas.seckillActivityId) {
        delete objParmas.seckillActivityId
      }
      let province = [], mcity = []
      if (!objParmas.wholeCountry) {
        if (objParmas.provinceCodes && objParmas.provinceCodes.length) {
          objParmas.provinceCodes.map(item => {
            areaList1.map(child => {
              if (child.value == item) {
                province.push(child.label)
              }
            })
          })
        }
        if (objParmas.cityCodes && objParmas.cityCodes.length) {
          objParmas.cityCodes.map(item => {
            item.map(child => {
              city.map(son => {
                son.map(k => {
                  if (k.value == child) {
                    mcity.push(k.label)
                  }
                })
              })
            })
          })
        }
        if (mcity.length) {
          if (mcity.length < 3) {
            objParmas.city = mcity.join(',');
          } else {
            objParmas.city = mcity.splice(0, 3).join(',') + '等'
          }
        }
        let pList = [], nList = []
        city.map((item, index) => {
          if (objParmas.cityCodes[index] && (objParmas.cityCodes[index].length == city[index].length)) {
            areaList1.map(child => {
              if (child.value == objParmas.provinceCodes[index]) {
                pList.push(child.label)
              }
            })
          } else {
            objParmas.cityCodes[index].map(item => {
              city[index].map(child => {
                if (child.value == item) {
                  nList.push(child.label)
                }
              })
            })
          };
        })
        if (nList.length >= 3) {
          nList = nList.splice(0, 3).join('、') + '等多个城市'
        } else {
          nList = nList.length ? '及' + nList.join('、') + '等城市' : ''
        }
        if (pList.length) {
          objParmas.city = `${pList.join(',')}${nList}`
        }
      } else {
        objParmas.city = '全国'
      }

      if (objParmas.imgUrl) {
        objParmas.url = objParmas.imgUrl;
        delete objParmas.imgUrl;
      }
      objParmas.location = objParmas.location;
      objParmas.linkType == 8 && (objParmas.linkUrl = "");
      // console.log(objParmas,319);
      const { success,msg } = yield call(submit, { ...objParmas });
      if (success) {
        // if (moment(query.startDate).isAfter(moment().add(10, 'minutes'))) {
        //   message.success(`您设置的弹窗广告将在${query.startDate}后10分钟内生效，请关注`);
        // } else {
        //   message.success(`您设置的弹窗广告将在10分钟之内生效，请稍候`);
        // }
        //message.success(actionType=='add'?'新增成功':'编辑成功')
        if (JSON.stringify(payload) != '{}' && payload.AuditOk) {
          let advertisementBuoysId = msg
          yield put({ type: 'advertisementAuditsubmit', payload: { advertisementBuoysId, auditStatus: 1 } })
        } else {
          message.success(actionType == 'add' ? '新增成功' : '编辑成功')
          hashHistory.push('/home/advertisementAdmin/advertisingBuoysList?closeTab=true')
        }
        // hashHistory.push('/home/advertisementAdmin/advertisingBuoysList')
      }
      yield call(delay, 2000);
      yield put({ type: 'updateStore', payload: { btnLoading: false } })


    },
    //获取所有上架楼盘列表
    *getAllEstateList({ payload }, { put, call, select }) {
      let { projectList } = yield select((state) => state[tmpModule.namespace])
      const { rows, success, total, pageNo } = yield call(AllEstateList, { shelfStatus: "1", pageSize: 100000 });
      if (success) {
        yield put({ type: 'updateStore', payload: { projectList: rows, projectListTotal: total, projectListPageNo: pageNo } })
      }
    },
    //获取当前楼盘的活动或资讯列表
    *getActivityList({ payload }, { put, call, select }) {
      const { rows, success, total, pageNo } = yield call(allActivityList, { ...payload, pageSize: 10000, status: 1 });
      if (success) {
        console.log(rows)
        yield put({ type: 'updateStore', payload: { activityList: rows } })
      }
    },
     // 审核
     *advertisementAuditsubmit({payload},{put,call,select}){
      try {
        let {loadingGroup} = yield select((state) => state[tmpModule.namespace])
        loadingGroup[''+payload.auditStatus+''] = true
        yield put({ type: 'updateStore', payload: { loadingGroup: loadingGroup } })
        const {  success } = yield call(advertisementAudit,payload);
        if(success){
            message.success('操作成功')
            hashHistory.push('/home/advertisementAdmin/advertisingBuoysList?closeTab=true')
        }
        loadingGroup[''+payload.auditStatus+''] = false
            yield put({ type: 'updateStore', payload: { loadingGroup: loadingGroup } })

      } catch (error) {
        console.log(error)
      }
    }
  },
  // 存入状态机
  reducers: {
    updateStore(preState, action) {
      return Object.assign({}, preState, action.payload)
    },
  }
}
export default tmpModule

